package com.shanks.home.module.image;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

import com.shanks.home.R;

/**
 * SurfaceView
 * @author Shanks
 * @time 2014.05.28
 */
public class SurfaceViewActivity extends Activity {
	
	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.image_surface_view_activity);
		intiView();
		surfaceViewFunc();
	}
	
	private void intiView() {
		surfaceView = (SurfaceView)this.findViewById(R.id.image_surface_view_sv);
	}
	
	private void surfaceViewFunc() {
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(new Callback() {
			
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// 锁定整个SurfaceView
				Canvas canvas = surfaceHolder.lockCanvas();
				// 绘制背景
				Bitmap back = BitmapFactory.decodeResource(SurfaceViewActivity.this.getResources(), R.drawable.game_model);
				canvas.drawBitmap(back, 0, 0, null);
				// 绘制完成，释放画布，提交修改
				surfaceHolder.unlockCanvasAndPost(canvas);
				// 重新锁一次，避免被下次lockCanvas遮挡
				surfaceHolder.lockCanvas(new Rect(0, 0, 0, 0));
				surfaceHolder.unlockCanvasAndPost(canvas);
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				
			}
		});
		
		surfaceView.setOnTouchListener(onTouchListener);
	}
	
	private OnTouchListener onTouchListener = new OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				int cx = (int)event.getX();
				int cy = (int)event.getY();
				// 锁定SurviceView的局部区域，只更新局部区域
				Canvas canvas = surfaceHolder.lockCanvas(new Rect(cx - 50, cy - 50, cx + 50, cy + 50));
				// 保存canvas的状态
				canvas.save();
				// 旋转画布
				canvas.rotate(30, cx, cy);
				Paint paint = new Paint();
				paint.setColor(Color.RED);
				// 绘制红色方块
				canvas.drawRect(cx - 40, cy - 40, cx, cy, paint);
				// 恢复Canvas之前保存的状态
				canvas.restore();
				paint.setColor(Color.GREEN);
				// 绘制绿色方块
				canvas.drawRect(cx - 40, cy - 40, cx, cy, paint);
				// 绘制完成，释放画布，提交修改
				surfaceHolder.unlockCanvasAndPost(canvas);
			}
			return false;
		}
	};
}